{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里我们试图计算卡方检验中的卡方值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import chi2_contingency"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "数据加载"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 假设obs是一个二维数组，表示特征在不同类别下的观测频数\n",
    "# 例如：obs = [[10, 20], [30, 40]] 表示特征在类别1和类别2下的观测频数\n",
    "obs = [[10, 20], [30, 40]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算卡方统计量和p值\n",
    "chi2, p, dof, expected = chi2_contingency(obs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "卡方统计量: 0.4464285714285714\n",
      "p值: 0.5040358664525046\n",
      "期望频数: [[12. 18.]\n",
      " [28. 42.]]\n"
     ]
    }
   ],
   "source": [
    "print(f\"卡方统计量: {chi2}\")\n",
    "print(f\"p值: {p}\")\n",
    "print(f\"期望频数: {expected}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "my_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
